package cn.chiship.sdk.core.util;

import cn.chiship.sdk.core.base.BaseResult;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.Date;

/**
 * @author lijian
 */
public class FileUtil extends FileUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

	public static final String FMT1 = "yyyy-MM-dd";

	public static final String FMT2 = "yyyy-MM";

	public static final String FMT3 = "yyyy";

	public static final String FMT4 = "yyyy/MM/dd";

	public static final String FMT5 = "yyyy/MM";

	public static String getDatePath() {
		return getDatePath(FMT1);
	}

	public static String getDatePath(String pattern) {
		if (StringUtil.isNullOrEmpty(pattern)) {
			pattern = FMT1;
		}
		return DateUtils.parseDateToStr(pattern, new Date());
	}

	/**
	 * 网络资源转换二进制数组
	 * @param url 网络路径
	 * @return 二进制数组
	 */
	public static byte[] downLoadToByte(String url) {
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
			InputStream inStream = conn.getInputStream();
			return IoUtil.readInputStream(inStream);
		}
		catch (Exception e) {
			LOGGER.error("网络资源下载失败:{}", url);
		}
		return new byte[0];
	}

	/**
	 * 下载网络资源到本地
	 * @param url 网络路径
	 * @param savePath 文件保存路径
	 * @param saveName 文件名
	 * @return 结果
	 */
	public static BaseResult downloadFile(String url, String savePath, String saveName) {
		DataInputStream dataInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			dataInputStream = new DataInputStream(new URL(url).openStream());
			FileUtils.forceMkdir(new File(savePath));
			File file = new File(savePath, saveName);
			fileOutputStream = new FileOutputStream(file);
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			byte[] context = output.toByteArray();
			fileOutputStream.write(context);

			return BaseResult.ok(file.getAbsolutePath());
		}
		catch (MalformedURLException e) {
			return BaseResult.error(e.getLocalizedMessage());
		}
		catch (IOException e) {
			LOGGER.error("发生异常", e);
			return BaseResult.error(e.getLocalizedMessage());
		}
		finally {
			try {
				if (ObjectUtil.isNotEmpty(dataInputStream)) {
					dataInputStream.close();
				}
				if (ObjectUtil.isNotEmpty(fileOutputStream)) {
					fileOutputStream.close();
				}
			}
			catch (IOException e) {
				LOGGER.error("发生异常", e);
			}

		}
	}

	/**
	 * 下载网络资源转换Base64
	 * @param url 网络资源路径
	 * @return Base64
	 */
	public static String downLoadToBase64(String url) {
		String base64String = null;
		try {
			Base64.Encoder encoder = Base64.getEncoder();
			base64String = new String(encoder.encode(downLoadToByte(url)));
		}
		catch (Exception e) {
			LOGGER.error("发生异常", e);
		}
		return base64String;
	}

}
